<?php
/**
 * Created by PhpStorm.
 * User: 丶晓
 * Date: 2017/9/20
 * Time: 17:50
 */

namespace app\api\controller;


use think\Config;
use think\Db;
use think\Request;
use app\api\common\Tools;
use app\api\model\MiniappsModel;
use app\api\service\DataService;
use app\api\service\PayService;
use think\Validate;

class Alipay extends PayService
{
    // +++++++++++++++++++++++++++++++++++++++++++++++++++
    // | 用户购买模板 $_GET template_id and $_GET uid @xiao
    // | api: [ https://api.suyongw.com/alipay/template ]
    // | method: GET
    // | parm: {
    // |     uid : 平台用户ID
    // |     template_id : 微信小程序模板ID
    // |     isSrc : 是否返回 二维码图片地址 & 否则为 支付宝API下单链接
    // | }
    // +++++++++++++++++++++++++++++++++++++++++++++++++++
    public function template()
    {
        $Tools = new Tools();
        if (!isset($_GET['template_id']) or empty($_GET['uid'])) {
            return $Tools->error('Request fail!');
        }
        $template_id = $_GET['template_id']; // 商品参数整理
        $uid = $_GET['uid'];  // 商品参数整理

        if ((empty($template_id) and $template_id != 0) or empty($uid)) {
            return $Tools->error('Request lost!'); // 参数不全
        }

        /*  检测用户是否存在 */
        if (Db::table('wyz_userinfo')->where('id', 'eq', $uid)->count() != 1) {
            return $Tools->error('Undefind user id');
        }

        /* 获取购买的模板详情 */
        $DataService = new DataService();
        $temp = $DataService->Template($template_id);
        if (!$temp) {
            return $Tools->error('Undefind template id');
        }

        /* 是否已经购买了该模板 */
        if ($DataService->isBuyTemplate($uid, $template_id)) {
            return $Tools->error('You got this template!');
        }

        /* 免费模板购买 */
        if ($temp['price'] <= 0) {
            $Model = new MiniappsModel();
            if ($Model->addInfo('zeroPriceTemplate', ['uid' => $uid, 'template_id' => $template_id])) {
                return $Tools->success('Buy success!');
            }
            return $Tools->error('Buy fail!db error 302');
        }

        // 订单详情
        $parms = [
            'price' => $temp['price'],
            'source' => '【速用科技】小程序模板<' . $temp['source'] . '> version:' . $temp['version'],
            'describe' => '适用于:' . $temp['temp_use'] . '等领域，主要组件有：' . $temp['main_ele']
        ];
        $orderId = $this->addInfo('int_buyTemplate', ['template_id' => $template_id, 'uid' => $uid]);
        if ($orderId) {
            $parms['out_trade_no'] = 'TPL_' . Config::get('alipay.order_no');  // 订单号码生成
            $RES = $this->signPay('alipay', 'scan', $parms);
            if (isset($RES['msg']) and $RES['msg'] == 'Success' and $this->payProcess('ready_buy_template_alipay',
                    ['out_trade_no' => $parms['out_trade_no'], 'uid' => $uid, 'order_id' => $orderId, 'order_info' => $parms])) { // 写订单入库
                $isSrc = isset($_GET['isSrc']) and ($_GET['isSrc']) ? true : false; // 是否返回二维码图片地址
                return $Tools->success('Request success!', ['OrderId' => $orderId, $isSrc ? 'src' : 'link' => $isSrc ? 'http://qr.topscan.com/api.php?text=' . $RES['qr_code'] . '&w=500' : $RES['qr_code']]);
            }
        }
        return $Tools->error('Pay fail!');
    }

    // +++++++++++++++++++++++++++++++++++++++++++++++
    // | 用户充值速用币 $_GET price and $_GET uid @xiao
    // | api: [ https://api.suyongw.com/alipay/recharge ]
    // | method: GET
    // | parm: {
    // |     uid : 平台用户ID
    // |     price : 充值数量 必须为整数 integer
    // |     isSrc : 是否返回 二维码图片地址 & 否则为 支付宝API下单链接
    // | }
    // +++++++++++++++++++++++++++++++++++++++++++++++++++
    public function recharge()
    {
        $Tools = new Tools();
        if (!isset($_GET['price']) or !isset($_GET['uid'])) {
            return $Tools->error('Request fail!');
        }
        $price = $_GET['price']; // 价格
        $uid = $_GET['uid'];  // 商品参数整理

        if (empty($price) or empty($uid)) {
            return $Tools->error('Request lost!'); // 参数不全
        }

        /*  检测用户是否存在 */
        if (Db::table('wyz_userinfo')->where('id', 'eq', $uid)->count() != 1) {
            return $Tools->error('Undefind user id');
        }

        /*
         *        此处省略返利业务逻辑
         *        此处省略返利业务逻辑
         *        此处省略返利业务逻辑
         *        此处省略返利业务逻辑
         *        此处省略返利业务逻辑
         */

        $validate = new Validate([
            'price' => 'require|number|integer',
        ]);
        if (!$validate->check(['price' => $price])) {
            return $Tools->error($validate->getError());
        }


        // 订单详情
        $parms = [
            'price' => $price,
            'source' => '【速用科技】充值速用币 - 平台充值',
            'describe' => '速用平台专用虚拟币，可用于购买平台内相关业务内容及分发虚拟币等用途 - 详情了解 www.suyongw.com SuYong Co. &copy;2016-' . date('Y'),
        ];
        $orderId = $this->addInfo('int_recharge', ['uid' => $uid, 'price' => $price]);  // 生成购买订单
        if ($orderId) {
            $parms['out_trade_no'] = 'RC_' . Config::get('alipay.order_no');  // 订单号码生成
            $RES = $this->signPay('alipay', 'scan', $parms);
            if (isset($RES['msg']) and $RES['msg'] == 'Success' and $this->payProcess('ready_pay_recharge_alipay',
                    ['out_trade_no' => $parms['out_trade_no'], 'uid' => $uid, 'order_id' => $orderId, 'order_info' => $parms])) { // 写订单入库
                $isSrc = isset($_GET['isSrc']) and ($_GET['isSrc']) ? true : false; // 是否返回二维码图片地址
                return $Tools->success('Request success!', ['OrderId' => $orderId, $isSrc ? 'src' : 'link' => $isSrc ? 'http://qr.topscan.com/api.php?text=' . $RES['qr_code'] . '&w=500' : $RES['qr_code']]);
            }
        }
        return $Tools->error('Pay fail!');
    }


    public function redirect()  // 支付宝 同步回调方法
    {
        // +++++++++++++
        // |  未启用
        // +++++++++++++
        echo 'success';
        exit();
    }

    public function redirect_url(Request $request)  // 支付宝 异步回调方法
    {
        if (!$request->isPost() or !$request->post('trade_status')) { // 异步一定为POST回调
            return 'request fail!';
        }

        $DATA = $this->alipayReturn($request->post()); // 验证签名
        if (!$DATA) {
            echo 'fail!';
            exit();
        }

        /* 根据支付状态的业务处理 */
        switch ($request->post('trade_status')) {
            case 'WAIT_BUYER_PAY':  // 创建订单时完善表中信息
                $parm = [
                    'trade_no' => $DATA['trade_no'],
                    'out_trade_no' => $DATA['out_trade_no'],
                    'order_info' => json_encode([
                        'title' => $DATA['subject'],
                        'body' => $DATA['body'],
                        'time' => $DATA['gmt_create'],
                        'buyer' => $DATA['buyer_logon_id']
                    ], JSON_UNESCAPED_UNICODE),
                    'seller_id' => $DATA['seller_id'],
                    'sign' => $DATA['sign'],
                    'price' => $DATA['total_amount'],
                ];
                if (!$this->changeInfo('ready_alipay_order', $parm)) {
                    echo 'fail';// 待写入支付失败日志
                    exit();
                }
                break;
            case 'TRADE_SUCCESS':  // 完成支付
                $parm = [
                    'trade_no' => $DATA['trade_no'],
                    'out_trade_no' => $DATA['out_trade_no'],
                    'price' => $DATA['total_amount'],
                ];
                if (!$this->changeInfo('success_alipay_order', $parm)) {
                    echo 'fail';// 待写入支付失败日志
                    exit();
                }
                break;
        }
        echo 'success';
        exit();
    }

}